//
//  MovieDetailViewController.m
//  MansApp
//
//  Created by lanou3g on 15/7/13.
//  Copyright (c) 2015年 ACH. All rights reserved.
//

#import "MovieDetailViewController.h"

@interface MovieDetailViewController ()<UIWebViewDelegate>
//@property (nonatomic,strong) UIWebView *webView;
@property (nonatomic,assign) BOOL isLoadingFinished;
@property (nonatomic,strong) NSString *string;
@end

@implementation MovieDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *url = [NSString stringWithFormat:@"%@%@",kMovieDetailUrl,_idString];
    NSLog( @"string ==== %@",url);
    
    UIWebView *webV=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight - 50)];
    //webV.scalesPageToFit=YES;//自动对齐页面缩放适应屏幕  默认是适配文本字体的;
    webV.scrollView.showsVerticalScrollIndicator=NO;
    [self.view addSubview:webV];
    webV.delegate = self;
    //self.tabBarController.tabBar.hidden = YES;
    
    
    //1)json串里面拥有网页源代码
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
    [request setHTTPMethod:@"GET"];
    NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSMutableDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSString *string=[dic objectForKey:@"body"];
    
    

    //下面的代码可以适配图片的显示
    int width = kWidth/1.06;
    NSString *imgWidth = [NSString stringWithFormat:@"<img width=\"%d\" ",width];
    
    //string = [string stringByReplacingOccurrencesOfString:@"<img src=\" " withString:imgWidth];
    if (_temp == 1000) {
        string = [string stringByReplacingOccurrencesOfString:@"<img class=\"content-image\"" withString:imgWidth];
    }
    else
    {
        string = [string stringByReplacingOccurrencesOfString:@"<img " withString:imgWidth];
    }
    
    
    [webV loadHTMLString:string baseURL:nil];
    //webV.scalesPageToFit=YES;
    
    

    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //字体大小
    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '80%'"];
    //字体颜色
    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'gray'"];
    // 替换作者图像
    //int width = kWidth/10;
//    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('icon-user-img').src width = '50'"];
//    [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('icon-user-img').src width = '50'"];
    //[webView stringByEvaluatingJavaScriptFromString:authorIconJsStr];
}

//网页加载完毕
/*
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if (!_isLoadingFinished) {
        
        // 替换正文(将内容通过js代码插入到HTML模板)
        NSString *contentJsStr = [NSString stringWithFormat:@"document.getElementById('bodyMain').innerHTML ='%@';",_string];
        NSLog(@"替换 %@",_string);
        [webView stringByEvaluatingJavaScriptFromString:contentJsStr];  // 执行JS代码
        
 
        // 替换作者图像
        NSString *authorIconJsStr = [NSString stringWithFormat:@"document.getElementById('icon-user-img').src ='%@';",self.neModel.user[@"avatar_url"]];
        
        [webView stringByEvaluatingJavaScriptFromString:authorIconJsStr]; // 执行JS代码
        
        // 替换作者名
        NSString *authorNameJsStr = [NSString stringWithFormat:@"document.getElementById('author-name').innerHTML ='%@';", self.neModel.user[@"name"]];
        [webView stringByEvaluatingJavaScriptFromString:authorNameJsStr];   // 执行JS代码
        
        // 替换时间
        NSString *timeJsStr = [NSString stringWithFormat:@"document.getElementById('timeago').innerHTML ='%@';", self.neModel.created_at];
         
        [webView stringByEvaluatingJavaScriptFromString:timeJsStr];    // 执行JS代码
 
    }
    
}

- (void)jiexiMovieDetail:(NSString *)string
{
    [ACHNetWork GET:string success:^(id response) {
        NSString *strings = [response objectForKey:@"body"];
        NSLog(@"文字%@",strings);
<<<<<<< HEAD
        self.webView = [[UIWebView alloc]initWithFrame:self.view.frame];
=======
        
        
        
        self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
        self.webView.delegate = self;
>>>>>>> b3ae34d9a751ceb03583e40da9def86d047d8cf4
        [_webView loadHTMLString:strings baseURL:nil];
        [self.view addSubview:_webView];
        _webView.delegate = self;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
*/
#pragma mark - UIWebViewDelegate
//- (void)webViewDidFinishLoad:(UIWebView *)webView{
//    
//        //修改服务器页面的meta的值
//        NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];
//        [webView stringByEvaluatingJavaScriptFromString:meta];
//  
//
//}

/*
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //NSString *string = [NSString stringWithFormat:@"%@%@",kMovieDetailUrl,_idString];
    //若已经加载完成，则显示webView并return
    if(_isLoadingFinished)
    {
        [self.webView setHidden:NO];
        return;
    }
    
    //js获取body宽度
    NSString *bodyWidth= [webView stringByEvaluatingJavaScriptFromString: @"document.body.scrollWidth"];
    
    int widthOfBody = [bodyWidth intValue];
    
    //获取实际要显示的html
    NSString *html = [self htmlAdjustWithPageWidth:widthOfBody
                                              html:_string
                                           webView:webView];
    
    //设置为已经加载完成
    _isLoadingFinished = YES;
    //加载实际要现实的html
    [self.webView loadHTMLString:html baseURL:nil];
}

//获取宽度已经适配于webView的html。这里的原始html也可以通过js从webView里获取
- (NSString *)htmlAdjustWithPageWidth:(CGFloat )pageWidth
                                 html:(NSString *)html
                              webView:(UIWebView *)webView
{
    NSMutableString *str = [NSMutableString stringWithString:html];
    //计算要缩放的比例
    CGFloat initialScale = webView.frame.size.width/pageWidth;
    //将</head>替换为meta+head
    NSString *stringForReplace = [NSString stringWithFormat:@"<meta name=\"viewport\" content=\" initial-scale=%f, minimum-scale=0.1, maximum-scale=2.0, user-scalable=yes\"></head>",initialScale];
    
    NSRange range =  NSMakeRange(0, str.length);
    //替换
    [str replaceOccurrencesOfString:@"</head>" withString:stringForReplace options:NSLiteralSearch range:range];
    return str;
}

*/


//- (void)webViewDidFinishLoad:(UIWebView *)webView
//{
//    [_webView stringByEvaluatingJavaScriptFromString:
//     @"var script = document.createElement('script');"
//     "script.type = 'text/javascript';"
//     "script.text = \"function ResizeImages() { "
//     "var src,oldwidth;"
//     "var maxwidth = 300.0;" // UIWebView中显示的图片宽度
//     "for(i=0;i <document.images.length;i++){"
//     "src = document.images[i];"
//     "if(src.width > maxwidth){"
//     "oldwidth = myimg.width;"
//     "src.width = maxwidth;"
//     "}"
//     "}"
//     "}\";"
//     "document.getElementsByTagName('head')[0].appendChild(script);"];
//    [_webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
//    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '120%'";
//    
//    [_webView stringByEvaluatingJavaScriptFromString:str];
//    
//}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
